#!/usr/bin/env python
# CowPod v0.1
#

import os
import os.path as path
import urllib
import feedparser # **
import eyeD3 # **
import time

FEEDS = path.join(os.environ['HOME'],'feeds')
OUTDIR = path.join(os.environ['HOME'],'podcast')
OUT = ''

if not path.exists(OUTDIR):
    os.mkdir(OUTDIR)

def get(url):
    f = urllib.urlopen(url)
    data = f.read()
    f.close()
    return data

def download(url,lfile):
    rfile = urllib.urlopen(url)

    if type(lfile) in (str,unicode) :
        lfile = file(lfile,'w')

    data = '-'
    while data:
        data = rfile.read(10000)
        lfile.write(data)

    lfile.close()
    rfile.close()
        

def main():
    
    f = file(FEEDS)
    feeds = f.readlines()
    f.close()

    for url in feeds:

        f = feedparser.parse(url)

        ftitle = f.feed.title
        print 'Parsing',ftitle

        plurl = path.join(OUTDIR,ftitle)
        if not path.exists(plurl):
            os.mkdir(plurl)

        for entry in f.entries:

            d = entry.updated
            date = d[12:16] + d[8:11] + d[5:7] + '_' + d[17:19] + d[20:22] + d[23:25] # il mese va trasformato in cifre

            ext = entry.link[entry.link.rindex('.'):]
            lurl = path.join(plurl,date)+ext

            if path.exists(lurl):
                continue

            print '\t',entry.title,'('+date+')'

            if ext=='.it':
                print 'I can\'t manage this.'
                continue

            download(entry.link,lurl)

            if ext=='.mp3':

                tag = eyeD3.Tag()
                tag.link(lurl)
                tag.setVersion(eyeD3.ID3_V2)
                tag.setArtist(ftitle)
                tag.setTitle(entry.title)
                if not tag.update():
                    print 'Id3tag not setted'

            

if __name__=='__main__':
    main()
